import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router';
import store from '@/store'
import { removePending } from '@/api/request'
import NotFound from '@/views/404'
import homePage from '@/views/'
import envsPage from '@/views/envs'

const files = require.context('.', false, /\.js$/)
let modules = []

files.keys().forEach(fileName  => {
  if (fileName.indexOf('index.js') ==-1){
    let _fileConfig = files(fileName)
    modules = modules.concat(_fileConfig.default||_fileConfig)
  }
})

const HomePage = [{
  path: '/home/:active?',
  name: 'home',
  component: homePage,
  meta:{ nav: true, login:false }
}]
const EnvsPage = [{
  path: '/envs',
  name: 'envs',
  component: envsPage,
}]
const homeRoute = [{path: '/', redirect:'/home'}]
const nomatched = [{ path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound }] // 未知页面转向首页
const routes = homeRoute.concat(HomePage, EnvsPage, modules.concat(nomatched))

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    return {
      el: 'body',
      top: 0,
    }
  },
})

export default router

// 已登录则不允许访问的页面名单
const login_redirect_page = ['login','register','findpwd','resetpwd','twoverify','sendemail','activationsuccess']
//1、匹配所有路由记录，验证登录查看页面权限； 2、在路由成功跳转时，取消from路由页面的相关数据请求
router.beforeEach((to, from) => {
  if (to.matched.some(page => page.meta.login) && !store.state.user.api_token) {
      router.push({
          name: 'login',
          query:{curl:to.fullPath}
      });
  } else if (store.state.user.api_token &&  login_redirect_page.includes(to.name)) {  // 判断已经登录则不再访问列表中的页面
      router.push({
          name: 'home'
      });
  } else {
      removePending(from.name, true) //取消from路由页面所有数据请求cacel设置为true的ajax请求
      return true
  }
});
